package com.cuiweiyou.contactsfromfile;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.leon.lfilepickerlibrary.LFilePicker;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.selectFileTextView)
    TextView selectFileTextView;

    @BindView(R.id.listView)
    ListView listView;

    ContactAdapter listAdapter;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String contactBean = msg.obj.toString();
            Log.e("ard", "添加了：" + contactBean);
            listAdapter.addInject(contactBean);

            int sizeNumbers = listAdapter.getData().size();
            int sizeInjected = listAdapter.getInjected().size();

            if (sizeInjected >= sizeNumbers) {
                Toast.makeText(MainActivity.this, "导入完毕！", Toast.LENGTH_LONG).show();
                selectFileTextView.setEnabled(false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initPermissions();
    }

    @OnClick(R.id.selectFileTextView)
    public void onSelectFileViewClick() {
        startMediaIntent();
    }

    private void startMediaIntent() {
        //        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //        //intent.setType(“image/*”);//选择图片
        //        //intent.setType(“audio/*”); //选择音频
        //        //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
        //        //intent.setType(“video/*;image/*”);//同时选择视频和图片
        //        intent.setType("*/*");//无类型限制
        //        intent.addCategory(Intent.CATEGORY_OPENABLE);
        //        startActivityForResult(intent, 1);

        new LFilePicker()
                .withActivity(MainActivity.this)
                .withRequestCode(Constant.NUMBER_13)
                .withStartPath("/storage/emulated/0")
                .withIsGreater(false)
                .withMutilyMode(false)
                .withFileSize(5000 * 1024)
                .withFileFilter(new String[]{".txt", ".png", ".docx"})
                .start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //        if (resultCode == Activity.RESULT_OK) {
        //            Uri uri = data.getData();
        //            String filePath = UriUtil.getFilePath(this, uri);
        //            if (!TextUtils.isEmpty(filePath)) {
        //                selectFileTextView.setText(filePath);
        //            }
        //        }

        if (resultCode == RESULT_OK) {
            if (requestCode == Constant.NUMBER_13) {
                List<String> list = data.getStringArrayListExtra("paths"); // 单选 withMutilyMode(false)
                if (null != list && list.size() > 0) {
                    String filePath = list.get(0);
                    tudo(filePath);
                }
            }
        } else if (Constant.NUMBER_11 == requestCode) {
            initPermissions();
        }
    }

    private void tudo(String filePath) {
        Log.e("ard", "文件：" + filePath);

        selectFileTextView.setText(filePath);

        List<String> contacts = ContactUtil.getContactsFromFile(filePath);
        if (null != contacts && contacts.size() > 0) {
            Log.e("ard", "号码数量：" + contacts.size());

            listAdapter.setData(contacts);

            injectToContact(contacts);
        }
    }

    private void initView() {
        selectFileTextView.setEnabled(true);
        listAdapter = new ContactAdapter(this, null);
        listView.setAdapter(listAdapter);
    }

    private void injectToContact(final List<String> contacts) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ContactUtil.inject(MainActivity.this, contacts, handler);
            }
        }).start();
    }

    //////////

    private void initPermissions() {
        // 开始请求权限
        MainActivityPermissionsDispatcher.obtainLocationWithPermissionCheck(MainActivity.this);
    }

    /**
     * 得到权限
     */
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    public void obtainLocation() {
        initView();
    }

    // 提示为什么需要该权限
    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    public void showRationaleForPermission(final PermissionRequest request) {

        PermissionTool.showPermissionDialog(MainActivity.this, new PermissionTool.OnNeedPermissionAgreeBack() {
            @Override
            public void agree(boolean authorized) {
                if (authorized) {
                    request.proceed(); // 系统申请框
                } else {
                    finish();
                }
            }
        });
    }

    // 被拒绝
    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    public void showDeniedForLocation() {
        PermissionTool.showPermissionRejectedDialog(this);
    }

    // 被拒绝并且勾选了不再提醒
    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})
    public void showNeverAskForLocation() {

        PermissionTool.requestPermissionFromSettingDialog(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
